<template>
  <div class="history-container">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
      <el-form :model="queryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="queryParams.keyword" clearable placeholder="请输入模糊查询关键字"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="申请批次">
              <el-input v-model="queryParams.batchNo" clearable placeholder="请输入申请批次"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="申请人">
              <el-input v-model="queryParams.applicantName" clearable placeholder="请输入申请人姓名"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="handleQuery" v-reclick="1000"> 查询 </el-button>
              <el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="tableLoading" 
        tooltip-effect="light" 
        row-key="id" 
        border
      >
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column prop="batchNo" label="申请批次" show-overflow-tooltip />
        <el-table-column prop="requestNo" label="申请号" show-overflow-tooltip />
        <el-table-column prop="storeTypeName" label="分类名称" show-overflow-tooltip />
        <el-table-column prop="materialName" label="物资名称" show-overflow-tooltip />
        <el-table-column prop="materialPrice" label="物资单价" show-overflow-tooltip />
        <el-table-column prop="quantity" label="申请数量" show-overflow-tooltip />
        <el-table-column prop="unit" label="单位" show-overflow-tooltip />
        <el-table-column prop="materialPriceTotal" label="物资总价" show-overflow-tooltip />
        <el-table-column prop="applicantName" label="申请人姓名" show-overflow-tooltip />
        <el-table-column prop="receiverName" label="接收人姓名" show-overflow-tooltip />
        <el-table-column prop="requestTime" label="申请时间" show-overflow-tooltip />
        <el-table-column prop="expectedDate" label="预期时间" show-overflow-tooltip />
        <el-table-column prop="statusNewOrChange" label="状态" show-overflow-tooltip>
          <template #default="scope">
            <g-sys-dict v-model="scope.row.statusNewOrChange" code="StatusNewOrChangeEnum" />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              icon="ele-View" 
              size="small" 
              text 
              type="primary" 
              @click="handleViewProcess(scope.row)"
            > 
              查看流程 
            </el-button>
            <el-button 
              icon="ele-Delete" 
              size="small" 
              text 
              type="danger" 
              @click="handleDelete(scope.row)"
              :loading="scope.row.deleting"
            > 
              删除 
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination 
        v-model:currentPage="tableParams.page"
        v-model:page-size="tableParams.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :total="tableParams.total"
        size="small"
        background 
      />
    </el-card>

    <!-- 流程查看对话框 -->
    <el-dialog
      v-model="showProcessDialog"
      :title="`${selectedRecord?.requestNo || ''} - 审批流程`"
      width="80%"
      :close-on-click-modal="false"
    >
      <ProcessSteps 
        v-if="processSteps.length > 0"
        :steps="processSteps" 
        :showDetails="true"
      />
      <div v-else class="no-process-info">
        <el-empty description="暂无流程信息" />
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStoreOutboundApi } from '/@/api/store/storeOutbound';
import { useStoreProcessRecordApi } from '/@/api/store/storeProcessRecord';
import ProcessSteps from './ProcessSteps.vue';

const storeOutboundApi = useStoreOutboundApi();
const storeProcessRecordApi = useStoreProcessRecordApi();

const tableLoading = ref(false);
const tableData = ref([]);

const queryParams = reactive({
  keyword: '',
  batchNo: '',
  applicantName: '',
});

const tableParams = reactive({
  page: 1,
  pageSize: 20,
  total: 0,
});

// 流程查看相关状态
const showProcessDialog = ref(false);
const selectedRecord = ref(null);
const processSteps = ref([]);
const processLoading = ref(false);

// 查看流程
const handleViewProcess = async (row: any) => {
  selectedRecord.value = row;
  showProcessDialog.value = true;
  processLoading.value = true;
  
  try {
    const result = await storeProcessRecordApi.getProcessSteps(row.id, '出库');
    processSteps.value = result.data.result || [];
  } catch (error) {
    console.error('获取流程信息失败:', error);
    ElMessage.error('获取流程信息失败');
    processSteps.value = [];
  } finally {
    processLoading.value = false;
  }
};

// 查询操作
const handleQuery = async (params: any = {}) => {
  tableLoading.value = true;
  try {
    Object.assign(tableParams, params);
    const result = await storeOutboundApi.page(Object.assign({}, queryParams, tableParams));
    tableParams.total = result.data.result?.total || 0;
    tableData.value = result.data.result?.items || [];
  } catch (error) {
    console.error('查询失败:', error);
  } finally {
    tableLoading.value = false;
  }
};

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    keyword: '',
    batchNo: '',
    applicantName: '',
  });
  tableParams.page = 1;
  handleQuery();
};

// 删除记录
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条出库申请记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    row.deleting = true;
    await storeOutboundApi.delete({ id: row.id });
    ElMessage.success('删除成功');
    await handleQuery();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  } finally {
    row.deleting = false;
  }
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  tableParams.pageSize = val;
  tableParams.page = 1;
  handleQuery();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  tableParams.page = val;
  handleQuery();
};

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.history-container {
  padding: 16px;
}

:deep(.el-input), 
:deep(.el-select) {
  width: 100%;
}
</style>